import 'package:flutter/material.dart';
import 'package:flutter_shop/provide/left_category_nav.dart';
import '../service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_shop/routers/application.dart';
import 'package:provide/provide.dart';
import 'package:flutter_shop/provide/index.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  String homePageContent = '正在获取首页的内容....';

  GlobalKey<RefreshFooterState> _footerKey =
      new GlobalKey<RefreshFooterState>();

  @override
  bool get wantKeepAlive => true;

  //获取火爆专区数据时使用
  var page = 1;
  List<Map> hotGoodsList = [];

  @override
  void initState() {
    //_getHotGoods();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var fromData = {'lon': '115.02932', 'lat': '35.76189'};
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('百姓生活+'),
        ),
        body: FutureBuilder(
          future: request('homePageContent', fromData: fromData),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              var data = jsonDecode(snapshot.data.toString());
//                List<Map> swiperDataList =
//                    (data['data']['slides'] as List).cast();
              //dart中尽量避免使用cast（）数据量多的时候开销大,以下是等效做法
              List<Map> swiperDataList = List<Map>.from(data['data']['slides']);
              List<Map> navigatorList =
                  List<Map>.from(data['data']['category']);
              String adPicture =
                  data['data']['advertesPicture']['PICTURE_ADDRESS'];
              String leaderPicture = data['data']['shopInfo']["leaderImage"];
              String leaderPhone = data['data']['shopInfo']["leaderPhone"];

              Map integralMallPicData = data['data']['integralMallPic'];
              Map saomaData = data['data']['saoma'];
              Map newUserData = data['data']['newUser'];
              List<Map> favorableList = List<Map>.from({
                integralMallPicData,
                saomaData,
                newUserData,
              });

              List<Map> recommendList =
                  List<Map>.from(data['data']['recommend']);

              String floor1Title = data['data']['floor1Pic']['PICTURE_ADDRESS'];
              String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS'];
              String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS'];

              List<Map> floor1 = List<Map>.from(data['data']['floor1']);
              List<Map> floor2 = List<Map>.from(data['data']['floor2']);
              List<Map> floor3 = List<Map>.from(data['data']['floor3']);
              return EasyRefresh(
                refreshFooter: ClassicsFooter(
                  key: _footerKey,
                  bgColor: Colors.white,
                  textColor: Colors.pink,
                  moreInfoColor: Colors.pink,
                  showMore: true,
                  noMoreText: '加载完成',
                  //由于目前不知道到底有多少数据因此不设置noMoreText
                  moreInfo: '加载中...',
                  loadReadyText: '上拉加载',
                ),
                child: ListView(
                  children: <Widget>[
                    SwiperDiy(
                      swiperDataList: swiperDataList,
                    ),
                    TopNavigator(
                      navigatorList: navigatorList,
                    ),
                    AdBanner(
                      adPicture: adPicture,
                    ),
                    LeaderPhone(
                      leaderPicture: leaderPicture,
                      leaderPhone: leaderPhone,
                    ),
                    Favorable(
                      favorableList: favorableList,
                    ),
                    Recommend(
                      recommendList: recommendList,
                    ),
                    FloorTitle(
                      picture_address: floor1Title,
                    ),
                    FloorContent(
                      floorGoodsList: floor1,
                    ),
                    FloorTitle(
                      picture_address: floor2Title,
                    ),
                    FloorContent(
                      floorGoodsList: floor2,
                    ),
                    FloorTitle(
                      picture_address: floor3Title,
                    ),
                    FloorContent(
                      floorGoodsList: floor3,
                    ),
                    _hotGoods(),
                  ],
                ),
                loadMore: () async {
                  print('加载更多的数据....');
                  var fromPage = {'page': page};
                  await request('homePageBelowConten', fromData: fromPage)
                      .then((val) {
                    var data = json.decode(val.toString());
                    List<Map> newGoodsList = List<Map>.from(data['data']);
                    setState(() {
                      hotGoodsList.addAll(newGoodsList);
                      page++;
                    });
                  });
                },
              );
            } else {
              return Text('正在加载中....');
            }
          },
        ),
      ),
    );
  }

//  //获取火爆专区的数据
//  void _getHotGoods() {
//    var fromPage = {'page': page};
//    request('homePageBelowConten', fromData: fromPage).then((val) {
//      var data = json.decode(val.toString());
//      List<Map> newGoodsList = List<Map>.from(data['data']);
//      setState(() {
//        hotGoodsList.addAll(newGoodsList);
//        page++;
//      });
//    });
//  }

  //火爆专区标题
  Widget hotTitle = Container(
    margin: const EdgeInsets.only(top: 10.0, bottom: 10.0),
    alignment: Alignment.center,
    color: Colors.transparent,
    child: Text('火爆专区'),
  );

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
          onTap: () {
            Application.router.navigateTo(
              context,
              '/detail?id=${val['goodsId']}',
            );
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: const EdgeInsets.all(5.0),
            margin: const EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(
                  val['image'],
                  width: ScreenUtil().setWidth(370),
                ),
                Text(
                  val['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.pink,
                    fontSize: ScreenUtil().setSp(26),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Text('￥${val['mallPrice']}'),
                    Text(
                      '￥${val['price']}',
                      style: TextStyle(
                        color: Colors.black26,
                        decoration: TextDecoration.lineThrough,
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text('上拉加载'); //获取列表为空
    }
  }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[
          hotTitle,
          _wrapList(),
        ],
      ),
    );
  }
}

//轮播组件（可以单独做一个文件存放也是可以的）
class SwiperDiy extends StatelessWidget {
  final List swiperDataList;

  const SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    //还可以通过ScreenUtil获取一些屏幕信息具体可以看GitHub上的开源flutter_screenutil
//    print('屏幕的像素密度：${ScreenUtil.pixelRatio}');
//    print('屏幕的宽度：${ScreenUtil.screenWidth}');
//    print('屏幕的高度：${ScreenUtil.screenHeight}');
    return Container(
      //使用宽高设置(字体设置setSp())
      height: ScreenUtil().setHeight(333),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemCount: swiperDataList.length,
        itemBuilder: (context, index) {
          return InkWell(
            onTap: () {
              Application.router.navigateTo(
                  context, '/detail?id=${swiperDataList[index]['goodsId']}');
            },
            child: Image.network(
              swiperDataList[index]['image'].toString(),
              fit: BoxFit.fill,
            ),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }
}

/*展示推荐的内容(自己写的)
class TopNavigator extends StatelessWidget {
  final List navigatorList;

  const TopNavigator({Key key, this.navigatorList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(260),
      color: Colors.white,
      margin: EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 5.0),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5,
          childAspectRatio: 1.0,
          crossAxisSpacing: 8.0,
        ),
        itemCount: categoryDataList.length,
        itemBuilder: (context, index) {
          return Column(children: <Widget>[
            CircleAvatar(
              backgroundColor: Colors.pink,
              child: Padding(
                padding: EdgeInsets.all(5.0),
                child: Image.network(
                  navigatorList[index]['image'].toString(),
                  fit: BoxFit.fitWidth,
                ),
              ),
            ),
            Text(navigatorList[index]['mallCategoryName']),
          ]);
        },
      ),
    );
  }
}*/

//顶部导航模块
class TopNavigator extends StatelessWidget {
  final List navigatorList;

  const TopNavigator({Key key, this.navigatorList}) : super(key: key);

  Widget _gridViewItemUI(BuildContext context, item, itemIndex) {
    return InkWell(
      onTap: ()  {
        Provide.value<IndexPageProvide>(context).setCurrentIndex(1);
        Provide.value<LeftCategoryNavProvide>(context)
            .setClickIndex(itemIndex, context);
        print('点击了导航图标');
      },
      child: Column(
        children: <Widget>[
          CircleAvatar(
            child: Image.network(
              item['image'],
              width: ScreenUtil().setWidth(95),
            ),
          ),
          Text(item['mallCategoryName']),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    int itemIndex = 0;
    if (this.navigatorList.length > 10) {
      this.navigatorList.removeRange(10, this.navigatorList.length);
    }
    return Container(
      color: Colors.white,
      height: ScreenUtil().setWidth(320),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(5.0),
        children: navigatorList.map((item) {
          return _gridViewItemUI(context, item, itemIndex++);
        }).toList(),
      ),
    );
  }
}

//广告导航模块
class AdBanner extends StatelessWidget {
  final String adPicture;

  const AdBanner({Key key, this.adPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(adPicture),
    );
  }
}

//店长电话模块
class LeaderPhone extends StatelessWidget {
  final String leaderPicture;
  final String leaderPhone;

  const LeaderPhone({Key key, this.leaderPicture, this.leaderPhone})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: _launchURL,
        child: Image.network(leaderPicture),
      ),
    );
  }

  void _launchURL() async {
    String url = 'tel:' + leaderPhone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}

//优惠模块
class Favorable extends StatelessWidget {
  final List favorableList;

  const Favorable({Key key, this.favorableList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(300),
      margin: const EdgeInsets.only(top: 10.0),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: favorableList.length,
        itemBuilder: (context, index) {
          return Image.network(
            favorableList[index]["PICTURE_ADDRESS"],
            width: ScreenUtil().setWidth(250),
          );
        },
      ),
    );
  }
}

/*推荐栏布局(自己写的)
class RecommendDiy extends StatelessWidget {
  final List recommendDataList;

  const RecommendDiy({Key key, this.recommendDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text(
          '商品推荐',
          style: TextStyle(
            color: Colors.pink,
          ),
        ),
        Container(
          height: ScreenUtil().setHeight(330),
          color: Colors.white,
          child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              childAspectRatio: 0.7,
            ),
            itemCount: recommendDataList.length,
            itemBuilder: (context, index) {
              return Column(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Image.network(
                    recommendDataList[index]['image'].toString(),
                  ),
                  Text(
                    "￥" + recommendDataList[index]['mallPrice'].toString(),
                  ),
                  Text(
                    "￥" + recommendDataList[index]['price'].toString(),
                    style: TextStyle(
                        color: Colors.grey,
                        decoration: TextDecoration.lineThrough),
                  ),
                ],
              );
            },
          ),
        )
      ],
    );
  }
}*/

//推荐模块
class Recommend extends StatelessWidget {
  final List recommendList;

  const Recommend({Key key, this.recommendList}) : super(key: key);

  //标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(
            color: Colors.black12,
            width: 0.5,
          ),
        ),
      ),
      child: Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //推荐商品单独项
  Widget _itemWidget(context, index) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(
            context, '/detail?id=${recommendList[index]['goodsId']}');
      },
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: const EdgeInsets.all(2.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            left: BorderSide(color: Colors.black12, width: 0.5),
          ),
        ),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text(
              "￥${recommendList[index]['mallPrice'].toString()}",
            ),
            Text(
              "￥${recommendList[index]['price'].toString()}",
              style: TextStyle(
                  color: Colors.grey, decoration: TextDecoration.lineThrough),
            ),
          ],
        ),
      ),
    );
  }

  //横向列表
  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setHeight(330),
      margin: EdgeInsets.only(top: 1.0),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context, index) {
          return _itemWidget(context, index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(390),
      margin: const EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[
          _titleWidget(),
          _recommendList(),
        ],
      ),
    );
  }
}

//楼层标题
class FloorTitle extends StatelessWidget {
  // ignore: non_constant_identifier_names
  final String picture_address;

  const FloorTitle({Key key, this.picture_address}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(8.0),
      child: Image.network(picture_address),
    );
  }
}

//楼层商品列表
class FloorContent extends StatelessWidget {
  final List floorGoodsList;

  const FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          _firstRowGoods(context),
          _otherGoods(context),
        ],
      ),
    );
  }

  Widget _firstRowGoods(BuildContext context) {
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodsList[0]),
        Column(
          children: <Widget>[
            _goodsItem(context, floorGoodsList[1]),
            _goodsItem(context, floorGoodsList[2]),
          ],
        ),
      ],
    );
  }

  Widget _otherGoods(BuildContext context) {
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodsList[3]),
        _goodsItem(context, floorGoodsList[4]),
      ],
    );
  }

  Widget _goodsItem(BuildContext context, Map goods) {
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: () {
          Application.router
              .navigateTo(context, '/detail?id=${goods['goodsId']}');
          print('点击了楼层商品');
        },
        child: Image.network(
          goods['image'],
        ),
      ),
    );
  }
}
